package edu.ccut.saturn.studio.dialog.webcontextdialog;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.dialog.TableViewerContentProvider;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnWebContextNode;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnWebContextParameter;

public class WebContextDialog extends TitleAreaDialog {
	
	private Label idLabel;
	private Text idText;
	private TableViewer tableViewer;
	
	private Table table;
	
	private Text nameText, descriptionText;
	
	private Label nameLabel, descriptionLabel;
	
	private SaturnWebContextNode saturnWebContextNode;
	
	private List<SaturnWebContextParameter> saturnWebContextParameterList;
	
	public WebContextDialog(Shell parentShell, SaturnWebContextNode saturnWebContextNode) {
		super(parentShell);
		this.saturnWebContextNode = saturnWebContextNode;
		this.copyList(saturnWebContextNode.getSaturnWebContextParameterList());
	}
	
	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(SelectionCandidate.SETTING_ATTRIBUTE + saturnWebContextNode.getName());
		return contents;
	}
	
	@Override
	protected Control createDialogArea(Composite parent) {

		getShell().setText(SelectionCandidate.ATTRIBUTE_SETTING);
		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));
		Composite area = (Composite) super.createDialogArea(parent);

		final Composite composite = new Composite(area, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		composite.setLayout(gridLayout);

		idLabel = new Label(composite, SWT.NONE);
		final GridData gd_idLabel = new GridData();
		gd_idLabel.verticalIndent = 5;
		gd_idLabel.horizontalIndent = 3;
		idLabel.setLayoutData(gd_idLabel);
		idLabel.setText("ID");

		idText = new Text(composite, SWT.READ_ONLY | SWT.BORDER);
		idText.setTextLimit(50);
		final GridData gd_idText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_idText.verticalIndent = 5;
		gd_idText.horizontalIndent = 10;
		gd_idText.heightHint = 14;
		idText.setLayoutData(gd_idText);

		nameLabel = new Label(composite, SWT.NONE);
		final GridData gd_nameLabel = new GridData();
		gd_nameLabel.verticalIndent = 5;
		gd_nameLabel.horizontalIndent = 3;
		nameLabel.setLayoutData(gd_nameLabel);
		nameLabel.setText(Messages.getString("WebContextDialog.Name"));  //$NON-NLS-1$

		nameText = new Text(composite, SWT.BORDER);
		nameText.setTextLimit(50);
		final GridData gd_nameText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_nameText.heightHint = 14;
		gd_nameText.verticalIndent = 5;
		gd_nameText.horizontalIndent = 10;
		nameText.setLayoutData(gd_nameText);

		descriptionLabel = new Label(composite, SWT.NONE);
		final GridData gd_descriptionLabel = new GridData(SWT.LEFT, SWT.TOP, false, false);
		gd_descriptionLabel.verticalIndent = 10;
		gd_descriptionLabel.horizontalIndent = 3;
		descriptionLabel.setLayoutData(gd_descriptionLabel);
		descriptionLabel.setText(Messages.getString("WebContextDialog.description"));  //$NON-NLS-1$
		
		descriptionText = new Text(composite, SWT.V_SCROLL | SWT.BORDER | SWT.WRAP);
		descriptionText.setTextLimit(200);
		final GridData gd_descriptionText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_descriptionText.heightHint = 66;
		gd_descriptionText.verticalIndent = 5;
		gd_descriptionText.horizontalIndent = 10;
		descriptionText.setLayoutData(gd_descriptionText);

		final Group group = new Group(composite, SWT.NONE);
		group.setLayout(new FormLayout());
		group.setText(Messages.getString("WebContextDialog.WebContext"));  //$NON-NLS-1$
		group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));

		tableViewer = new TableViewer(group, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
		table = tableViewer.getTable();
		final FormData fd_table = new FormData();
		fd_table.bottom = new FormAttachment(100, -5);
		fd_table.top = new FormAttachment(0, 5);
		fd_table.right = new FormAttachment(100, -75);
		fd_table.left = new FormAttachment(0, 5);
		table.setLayoutData(fd_table);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		tableViewer.setContentProvider(new TableViewerContentProvider());
		tableViewer.setLabelProvider(new WebContextLabelProvider());
		
		tableViewer.setColumnProperties(new String[] { "id", "key",	"scope", "newKey", "newScope" });
		CellEditor[] cellEditor = new CellEditor[5];
		cellEditor[0] = null;
		cellEditor[1] = new TextCellEditor(tableViewer.getTable());
		cellEditor[2] = new ComboBoxCellEditor(tableViewer.getTable(), SelectionCandidate.scopes, SWT.READ_ONLY);
		cellEditor[3] = new TextCellEditor(tableViewer.getTable());
		cellEditor[4] = new ComboBoxCellEditor(tableViewer.getTable(), SelectionCandidate.scopes, SWT.READ_ONLY);

		tableViewer.setCellEditors(cellEditor);
		tableViewer.setCellModifier(new MyCellModifierWebContext(tableViewer));
		
		final TableColumn contextIDColumn = new TableColumn(table, SWT.NONE);
		contextIDColumn.setWidth(75);
		contextIDColumn.setText(Messages.getString("WebContextDialog.ContextID")); //$NON-NLS-1$

		final TableColumn contextKeyColumn = new TableColumn(table, SWT.NONE);
		contextKeyColumn.setWidth(90);
		contextKeyColumn.setText(Messages.getString("WebContextDialog.ContextKeyValue")); //$NON-NLS-1$

		final TableColumn contextScopeColumn = new TableColumn(table, SWT.NONE);
		contextScopeColumn.setWidth(90);
		contextScopeColumn.setText(Messages.getString("WebContextDialog.ContextScope")); //$NON-NLS-1$

		final TableColumn newContextKeyColumn = new TableColumn(table, SWT.NONE);
		newContextKeyColumn.setWidth(100);
		newContextKeyColumn.setText(Messages.getString("WebContextDialog.NewContextKeyValue")); //$NON-NLS-1$

		final TableColumn newContextScopeColumn = new TableColumn(table, SWT.NONE);
		newContextScopeColumn.setWidth(100);
		newContextScopeColumn.setText(Messages.getString("WebContextDialog.NewContextScope")); //$NON-NLS-1$
		
		tableViewer.setInput(revertScopeToSurface(saturnWebContextParameterList));

		final Button addButton = new Button(group, SWT.NONE);
		addButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				openAddDialog();
			}
		});
		final FormData fd_addButton = new FormData();
		fd_addButton.top = new FormAttachment(table, 0, SWT.TOP);
		fd_addButton.left = new FormAttachment(table, 15, SWT.RIGHT);
		fd_addButton.right = new FormAttachment(100,-15);
		addButton.setLayoutData(fd_addButton);
		addButton.setText(SelectionCandidate.ADD_BUTTON);

		final Button editButton = new Button(group, SWT.NONE);
		editButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					openEditDialog((SaturnWebContextParameter) selection.getFirstElement());
					tableViewer.refresh();
				}
			}
		});
		final FormData fd_editButton = new FormData();
		fd_editButton.top = new FormAttachment(addButton, 10, SWT.BOTTOM);
		fd_editButton.left = new FormAttachment(addButton, 0, SWT.LEFT);
		fd_editButton.right = new FormAttachment(addButton, 0, SWT.RIGHT);
		editButton.setLayoutData(fd_editButton);
		editButton.setText(SelectionCandidate.EDIT_BUTTON);

		final Button deleteButton = new Button(group, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked")
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				SaturnWebContextParameter saturnWebContextParameter = (SaturnWebContextParameter) selection.getFirstElement();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					saturnWebContextParameterList.remove(saturnWebContextParameter);
					reorder(saturnWebContextParameterList);
					tableViewer.setInput(revertScopeToSurface(saturnWebContextParameterList));
				}
			}
		});
		final FormData fd_deleteButton = new FormData();
		fd_deleteButton.top = new FormAttachment(editButton, 10, SWT.BOTTOM);
		fd_deleteButton.left = new FormAttachment(editButton, 0, SWT.LEFT);
		fd_deleteButton.right = new FormAttachment(editButton, 0, SWT.RIGHT);
		deleteButton.setLayoutData(fd_deleteButton);
		deleteButton.setText(SelectionCandidate.DELETE_BUTTON);
		
		idText.setText(saturnWebContextNode.getId().trim());
		nameText.setText(saturnWebContextNode.getName().trim());
		descriptionText.setText(saturnWebContextNode.getDescription().trim());
		
		/**
		 * 名称不可为空
		 * 
		 * */
		nameText.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				if("".equals(nameText.getText().trim())){
					setErrorMessage(Messages.getString("WebContextDialog.NameLimit")); //$NON-NLS-1$
					getButton(IDialogConstants.OK_ID).setEnabled(false);
				}else{
					setErrorMessage(null);
					getButton(IDialogConstants.OK_ID).setEnabled(true);
				}
			}
		});
	
		return area;
	}
	
	@Override
	protected void buttonPressed(int buttonId) {
		if(saturnWebContextNode == null){
			return;
		}
		if (buttonId == IDialogConstants.OK_ID) {
			
			saturnWebContextNode.setDescription(descriptionText.getText().trim());
			saturnWebContextNode.setSaturnWebContextParameterList(revertScopeInXml(saturnWebContextParameterList));
			saturnWebContextNode.setName(nameText.getText().trim());
		}
		super.buttonPressed(buttonId);
	}
	
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		super.createButtonsForButtonBar(parent);
		getButton(IDialogConstants.OK_ID).setEnabled(true);
	}
	
	@Override
	protected Point getInitialSize() {
		return new Point(580, 460);
	}

	private void openAddDialog(){
		WebContextDialogForAdd a = new WebContextDialogForAdd(Display.getDefault().getShells()[0],saturnWebContextParameterList, saturnWebContextNode);
		a.open();
		tableViewer.setInput(revertScopeToSurface(saturnWebContextParameterList));
	}
	
	private void openEditDialog(SaturnWebContextParameter parameter){
		WebContextDialogForEdit a = new WebContextDialogForEdit(Display.getDefault().getShells()[0],parameter, saturnWebContextNode);
		a.open();
	}
	
	private void reorder(List<SaturnWebContextParameter> saturnWebContextParameterList){
		for(int i = 0 ;i<saturnWebContextParameterList.size();i++){
			SaturnWebContextParameter parameter = (SaturnWebContextParameter)saturnWebContextParameterList.get(i);
			parameter.setId(String.valueOf(i+1));
		}
	}
	
	private void copyList(List<SaturnWebContextParameter> list){
		List<SaturnWebContextParameter> listTemp = new ArrayList<SaturnWebContextParameter>();
		for(SaturnWebContextParameter parameter : list){
			SaturnWebContextParameter parameter2 = new SaturnWebContextParameter(parameter);
			listTemp.add(parameter2);
		}
		this.saturnWebContextParameterList = listTemp;
	}
	
	private List<SaturnWebContextParameter> revertScopeInXml(
			List<SaturnWebContextParameter> saturnWebContextParameterList){
		for(int i = 0; i < saturnWebContextParameterList.size(); i++){
			if("logic".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("1");
			} else if("request".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("2");
			} else if("session".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("5");
			} else if("application".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("10");
			}
			
			if("logic".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("1");
			} else if("request".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("2");
			} else if("session".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("5");
			} else if("application".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("10");
			}
		}
		return saturnWebContextParameterList;
	}
	
	private List<SaturnWebContextParameter> revertScopeToSurface(
			List<SaturnWebContextParameter> saturnWebContextParameterList){
		for(int i = 0; i < saturnWebContextParameterList.size(); i++){
			if("1".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("logic");
			} else if("2".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("request");
			} else if("5".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("session");
			} else if("10".equals(saturnWebContextParameterList.get(i).getScope())){
				saturnWebContextParameterList.get(i).setScope("application");
			}
			
			if("1".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("logic");
			} else if("2".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("request");
			} else if("5".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("session");
			} else if("10".equals(saturnWebContextParameterList.get(i).getNewScope())){
				saturnWebContextParameterList.get(i).setNewScope("application");
			}
		}
		return saturnWebContextParameterList;
	}
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}
}
